//
//  CZRankingViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/22.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZRankingViewController.h"
#import "CZRankingCell.h"
static NSString *const rank_cell = @"rank_cell";

@interface CZRankingViewController () <UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *rankTableView;
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *rankArray;
@property (nonatomic, copy) NSDictionary *userDic;
@property (weak, nonatomic) IBOutlet UIImageView *kingImageView;
@property (nonatomic, strong) LGRefreshView *refreshView;
@property (nonatomic, assign) NSInteger currentPage;
@property (weak, nonatomic) IBOutlet UILabel *honorLabel;

@property (nonatomic, copy) NSArray *displayArray;

@end

@implementation CZRankingViewController

- (NSArray * __nonnull)displayArray {
    if (!_displayArray) {
        _displayArray = [[NSArray alloc] init];
    }
    return _displayArray;
}

- (NSMutableArray *__nonnull)rankArray {
    if (!_rankArray) {
        _rankArray = [[NSMutableArray alloc] init];
    }
    return _rankArray;
}

- (NSDictionary *)userDic {
    if (!_userDic) {
        _userDic = [[NSDictionary alloc] init];
    }
    return _userDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _currentPage = 1;
    self.title = @"排行榜";
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(postRankData) name:CZLoginSuccessNotification object:nil];
    
    [(UIView*)[self.navigationController.navigationBar.subviews objectAtIndex:0] setAlpha:1.f];
    self.rankTableView.estimatedRowHeight = 80;
    self.rankTableView.rowHeight = UITableViewAutomaticDimension;
    [self.rankTableView registerNib:[UINib nibWithNibName:@"CZRankingCell" bundle:nil] forCellReuseIdentifier:rank_cell];
    self.rankTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.rankTableView.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    
    _refreshView = [LGRefreshView refreshViewWithScrollView:self.rankTableView
                                             refreshHandler:^(LGRefreshView *refreshView){
                                                 [self.rankTableView.mj_footer setState:(MJRefreshStateIdle)];
                                                 _currentPage = 1;
                                                 [self postRankData];
                                             }];
    _refreshView.center = CGPointMake(Main_Screen_Width / 2, _refreshView.center.y);
    _refreshView.tintColor = ThemeColor;
    _refreshView.backgroundColor = [UIColor clearColor];
    
    self.rankTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (_currentPage < 5) {
            _currentPage ++;
        }
        if (self.rankArray.count < 20 * _currentPage + 1) {
            self.displayArray = [self.rankArray copy];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.rankTableView reloadData];
            });
            [self.rankTableView.mj_footer endRefreshingWithNoMoreData];

        } else {
            self.displayArray = [self.rankArray subarrayWithRange:NSMakeRange(0, 20 * _currentPage + 1)];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.rankTableView reloadData];
            });
            [self.rankTableView.mj_footer endRefreshing];
        }
        
        
    }];
    self.rankTableView.mj_footer.hidden = YES;
    
    [self postRankData];
    // Do any additional setup after loading the view from its nib.
}

- (void)postRankData {
    [SVProgressHUD showWithStatus:@"获取排行榜数据中..."];
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/rank/index",APP_HOST];
    NSDictionary *param;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:User_Token]) {
        param = @{@"page" : @1, @"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token]};
    } else {
        param = @{@"page" : @1};
    }
    [GCZAFNetWorking POST:urlString params:param success:^(id response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSDictionary *rootDic = response[@"result"];
            NSArray *arr = rootDic[@"rankList"];
            
            [self.rankArray removeAllObjects];
            for (NSDictionary *dic in arr) {
                
                [self.rankArray addObject:dic];
            }
            
            NSDictionary *firstDic = self.rankArray.firstObject;
            if ([NSURL URLWithString:firstDic[@"logo"]]) {
                self.kingImageView.yy_imageURL = [NSURL URLWithString:firstDic[@"logo"]];

            } else {
                self.kingImageView.image = [UIImage imageNamed:@"logo"];
            }
            NSString *exp = firstDic[@"experience_point"];
            [self setRankDataWithEXP:exp label:self.honorLabel];
            
            if (!rootDic[@"myrank"] || (__bridge CFBooleanRef)rootDic[@"myrank"] == kCFBooleanFalse) {
                [self.rankArray insertObject:@{} atIndex:0];
            } else {
                [self.rankArray insertObject:rootDic[@"myrank"] atIndex:0];
            }
            if (self.rankArray.count > 20) {
                self.displayArray = [self.rankArray subarrayWithRange:NSMakeRange(0, 21)];
            } else {
                self.displayArray = [self.rankArray copy];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.rankTableView reloadData];
                self.rankTableView.mj_footer.hidden = NO;
                self.rankTableView.mj_footer.state  = MJRefreshStateIdle;
            });
        }
        [_refreshView endRefreshing];
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [_refreshView endRefreshing];
        [SVProgressHUD dismiss];
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.displayArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.row == 0 ? 90 : 82;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZRankingCell *cell = [tableView dequeueReusableCellWithIdentifier:rank_cell];
    NSDictionary *dic = self.rankArray[indexPath.row];
    if ([cell.contentView viewWithTag:1000]) {
        [[cell.contentView viewWithTag:1000] removeFromSuperview];
    }
    if (indexPath.row == 0) {
        UIView *bottomView = [[UIView alloc] init];
        bottomView.backgroundColor = GLOBAL_BACKGROUND_COLOR;
        [cell.contentView addSubview:bottomView];
        [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(cell.contentView);
            make.height.equalTo(@8);
        }];
        bottomView.tag = 1000;
    }
    if ([dic[@"logo"] containsString:@"http"]) {
        cell.rankingIcon.yy_imageURL = dic[@"logo"];
    } else {
        cell.rankingIcon.image = [UIImage imageNamed:@"logo"];
    }
    cell.userNameLabel.text = dic[@"nickname"];
    if (!dic[@"experience_point"]) {
        cell.rankLevelLabel.text = @"世界移民";
    } else {
        NSString *exp = dic[@"experience_point"];
        [self setRankDataWithEXP:exp label:cell.rankLevelLabel];
    }
    

    NSString *rank = dic[@"rank"];
    if (rank.integerValue != 1) {
        cell.vipImageView.hidden = YES;
    } else {
        cell.vipImageView.hidden = NO;
    }
    NSArray *rankIcons = @[@"icon_golden", @"icon_silver", @"icon_copper"];
    if (rank.integerValue > 0 && rank.integerValue < 4) {
        cell.rightImageView.image = [UIImage imageNamed:rankIcons[rank.integerValue - 1]];
        cell.rankNumberLabel.hidden = YES;
        cell.rightImageView.hidden = NO;
    } else {
        cell.rightImageView.hidden = YES;
        cell.rankNumberLabel.hidden = NO;
        if (rank.integerValue < 10) {
            cell.rankNumberLabel.text = [NSString stringWithFormat:@"0%d", rank.integerValue];
        } else {
            cell.rankNumberLabel.text = [NSString stringWithFormat:@"%d", rank.integerValue];
        }
        
    }
    if (!rank) {
        cell.rankNumberLabel.text = @"0";
    }
    return cell;
}

- (void)setRankDataWithEXP:(NSString *)exp label:(UILabel *)label{
    
    if (exp.integerValue  < 750 || exp.integerValue == 750) {
        label.text = @"世界移民";
    }
    if (exp.integerValue > 750 || exp.integerValue  == 1550) {
        label.text = @"流浪猎人";
    }
    if (exp.integerValue > 1550 || exp.integerValue == 2450) {
        label.text = @"猎人长";
    }
    if (exp.integerValue > 2450 || exp.integerValue == 3650) {
        label.text = @"法师";
    }
    
    if (exp.integerValue > 3650 || exp.integerValue == 5350) {
        label.text = @"祭祀";
        
    }
    if (exp.integerValue > 5350 || exp.integerValue == 8000) {
        label.text = @"酋长";
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
